﻿using AutoMapper;
using HamcoWcs.Contract;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractMes;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.MainTasks;
using HamcoWcs.Entitys.SubTasks;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.ForeEndModels.UITasks;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;

namespace HamcoWcs.Service.Common
{

    [AutoInject(typeof(IBaseTaskService), InjectType.Scope)]
    public class BaseTaskService : ScopeServiceBase, IBaseTaskService
    {
        private readonly ILoggerService _logger;
        private readonly IBaseConfigService _config;
        private readonly IMesCommunicateService _mesCommunicateService;
        public BaseTaskService(ILoggerService logger, IBaseConfigService config, IMesCommunicateService mesCommunicateService, IMapper mapper, WcsDbContext wcsDbContext)
            : base(wcsDbContext, mapper)
        {
            _logger = logger;
            _config = config;
            _mesCommunicateService = mesCommunicateService;
        }


        public bool UpdateSubTaskStatus(long taskId, EnumSubTaskStatus taskStatus)
        {
            var taskEnity = _wcsDbContext.SubTasks
                .Where(x => x.Id == taskId)
                .Include(x => x.MainTask)
                .FirstOrDefault();

            if (taskEnity == null) return false;
            if (taskEnity.TaskStatus == taskStatus.ToString()) return true;

            taskEnity.TaskStatus = taskStatus.ToString();
            //_logger.AddWcsRunLog(taskEnity.UnitId, $"{taskEnity.MainTask.TaskId}-{taskEnity.TaskSeq}状态置为{taskStatus}");

            switch (taskStatus)
            {
                case EnumSubTaskStatus.Ready:
                    ReadySubTask(taskEnity);
                    break;
                case EnumSubTaskStatus.OnProgress:
                    BeginToWorkSubTask(taskEnity);
                    break;
                case EnumSubTaskStatus.Finished:
                    return FinishSubTask(taskEnity);
                case EnumSubTaskStatus.NewTask:
                case EnumSubTaskStatus.Error:
                default:
                    break;
            }

            return _wcsDbContext.SaveChanges() > 0;
        }

        private void ReadySubTask(SubTask taskEnity)
        {
            _wcsDbContext.Update(taskEnity);
        }

        private void BeginToWorkSubTask(SubTask taskEnity)
        {
            //if (taskEnity.TaskSeq != 1)
            //{
            //    return;
            //}
            // TODO 当前设备名更改
            taskEnity.MainTask.CurrentMachine = taskEnity.FromLoc;
            taskEnity.MainTask.CurrentPosition = "";
            taskEnity.MainTask.CurrentType = "PORT";

            taskEnity.SendTime = DateTime.Now;
            taskEnity.StartTime = DateTime.Now;
            taskEnity.MainTask.TaskStatus = EnumMainTaskStatus.OnProgress.ToString();
            taskEnity.MainTask.ActiveSubTaskId = taskEnity.TaskSeq;
            _wcsDbContext.Update(taskEnity);
        }

        private bool FinishSubTask(SubTask taskEnity)
        {
            // TODO 当前设备名更改
            taskEnity.MainTask.CurrentMachine = taskEnity.ToLoc;
            taskEnity.MainTask.CurrentPosition = "";
            taskEnity.MainTask.CurrentType = "PORT";

            if (taskEnity.MainTask.MainTaskType == nameof(EnumMainTaskType.SrmCycleTask))
            {
                //taskEnity.FromLoc = taskEnity.MainTask.DesPosition;
                //taskEnity.ToLoc = taskEnity.MainTask.SrcPosition;


                string f = taskEnity.TaskSeq % 2 == 1 ? taskEnity.MainTask.DesPosition : taskEnity.MainTask.SrcPosition;
                string t = taskEnity.TaskSeq % 2 != 1 ? taskEnity.MainTask.DesPosition : taskEnity.MainTask.SrcPosition;

                taskEnity.MainTask.SubTasks.Add(new SubTask()
                {
                    TaskSeq = taskEnity.TaskSeq + 1,
                    UnitId = taskEnity.UnitId,
                    FromLoc = f,
                    ToLoc = t,
                    PlcName = taskEnity.MainTask.SrcMachine,
                    SubTaskType = nameof(EnumSubTaskType.SrmMoveTask),
                    TaskStatus = nameof(EnumSubTaskStatus.Ready),
                    TaskFrom = taskEnity.TaskFrom,
                });
                taskEnity.MainTask.TotalSubTaskNum++;
                taskEnity.MainTask.ActiveSubTaskId++;

                _wcsDbContext.Update(taskEnity.MainTask);
                _wcsDbContext.SaveChanges();
                return true;
            }


            var s = _config.GetConfigValue("CJVCV300TRANSPORTSTATE");
            if (taskEnity.FromLoc == "CJVCV300" && s == "1")
            {
                var countStr = _config.GetConfigValue("CURRENTCJVCV300TRANSPORTCOUNT");
                int count = int.Parse(countStr);
                count++;
                _config.SetConfigMsg("CURRENTCJVCV300TRANSPORTCOUNT", count.ToString());
            }


            taskEnity.CompleteTime = DateTime.Now;



            if (taskEnity.TaskSeq == taskEnity.MainTask.TotalSubTaskNum)
            {
                taskEnity.MainTask.TaskStatus = EnumMainTaskStatus.Finished.ToString();
                _wcsDbContext.Update(taskEnity.MainTask);
                //_logger.AddWcsRunLog(taskEnity.UnitId, $"主任务{taskEnity.MainTask.TaskId}置为{EnumMainTaskStatus.Finished}");
                return true;
            }


            taskEnity.MainTask.ActiveSubTaskId = taskEnity.TaskSeq + 1;
            var mainTask = _wcsDbContext.MainTasks.Include(x => x.SubTasks).FirstOrDefault(x => x.Id == taskEnity.MainTask.Id);

            // var mainTask = taskEnity.MainTask;
            var nextSubTask = mainTask.SubTasks.FirstOrDefault(x => x.TaskSeq == taskEnity.TaskSeq + 1);

            nextSubTask.TaskStatus = EnumSubTaskStatus.Ready.ToString();
            //_logger.AddWcsRunLog(taskEnity.UnitId, $"子任务{taskEnity.MainTask.TaskId}-{nextSubTask.TaskSeq}状态置为{nextSubTask.TaskStatus}");
            //if (nextSubTask.FromLoc.Contains("CJRGV") || nextSubTask.FromLoc.Contains("CJMIF"))
            if (nextSubTask.FromLoc.Contains("CJRGV"))
            {
                nextSubTask.TaskStatus = EnumSubTaskStatus.OnProgress.ToString();
                //_logger.AddWcsRunLog(taskEnity.UnitId, $"子任务{taskEnity.MainTask.TaskId}-{nextSubTask.TaskSeq}状态置为{nextSubTask.TaskStatus}");
            }

            mainTask.TaskStatus = EnumMainTaskStatus.OnProgress.ToString();
            _wcsDbContext.Update(taskEnity);
            return _wcsDbContext.SaveChanges() > 0;
        }

        public string ChangeMainTaskPriority(MainTaskChangePriorityDto dto)
        {
            MainTask mainTask = _wcsDbContext.MainTasks.FirstOrDefault(x => x.Id == dto.Id);
            if (mainTask == null) throw new System.Exception($"未找到当前任务，可能已完成或被删除");

            string priority = mainTask.Priority;
            mainTask.Priority = dto.Priority;

            _wcsDbContext.SaveChanges();
            _mesCommunicateService.PalletTransportPriorityChanged(mainTask.TaskId, mainTask.Priority);
            return $"调整任务{mainTask.TaskId}优先级{priority}->{dto.Priority}";
        }
    }
}
